package com.zxl.mytest9;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;

/**
 * 对象序列化操作，主要测试写入和读取一个未实现Serializable接口的对象
 * @author zxl
 *
 */
public class ObjectSerializable {
    
    private static final ThreadLocal<Map<String, Object>> FIELD_VALUE = new ThreadLocal<>();
    
    private static final String INDEX_KEY = "0index";
    
    public static void main(String[] args) throws Exception {
        Person person = new Child("abc", 12, 0);
//        Person person = new Child();
        recursionClass(person.getClass(),person);
//        byte[] bytes = serializable(person);
//        deSerializable(bytes);
//        toJson(person);
        
//        String name = "get$123";
//        System.out.println(name.matches("^get[A-Z\\_\\$]\\S*$"));
        
//        byte[] serializable = serializable(FIELD_VALUE.get());
//        Object obj = deSerializable(serializable);
        byte[] bytes = serializable(person);
        Object obj = deserializable(bytes);
        System.out.println(obj);
    }
    
    public static byte[] serializable(Object obj) throws Exception{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        byte[] byteArray = baos.toByteArray();
        System.out.println(byteArray.length);
        return byteArray;
    }
    
    public static Object deserializable(byte[] bytes) throws Exception{
    	ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    	ObjectInputStream ois = new ObjectInputStream(bais);
    	Object readObject = ois.readObject();
    	return readObject;
    }
    
    @SuppressWarnings("unchecked")
    public static Object deSerializable(byte[] bytes) throws Exception{
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object readObject = ois.readObject();
        Map<String, Object> map = (Map<String, Object>) readObject;
        Integer index = (Integer) map.remove(INDEX_KEY);
        String clsName  = (String) map.remove("1");
        Class<?> cls = Class.forName(clsName);
        List<Class<?>> clsList = new ArrayList<>(index);
        clsList.add(null);
        clsList.add(cls);
        for(int i = 1; i < index; i++){
            clsList.add(clsList.get(i).getSuperclass());
        }
        Constructor<?> constructor = cls.getConstructors()[1];
        Parameter[] parameters = constructor.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter.getType().getName());
        }
        //TODO 如此构造有问题，看下组装map的时候能否拿到构造参数和值
        Object obj = constructor.newInstance(new Object[]{null});
//        Object obj = cls.newInstance();
        String regex = "(\\d+)(?:.+)";
        Pattern pattern = Pattern.compile(regex);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Matcher matcher = pattern.matcher(key);
            if (matcher.find()) {
                String cid = matcher.group(1);
                Field field = clsList.get(Integer.valueOf(cid)).getDeclaredField(key.substring(1));
                field.setAccessible(true);
                field.set(obj, entry.getValue());
            }
//            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
        return obj;
    }
    
    public static void reflectClass(Object obj){
        Class<? extends Object> clazz = obj.getClass();
        //获取本类定义的所有字段,不包括继承的
        Field[] fields = clazz.getDeclaredFields();
        //获取继承的所有public字段
        Field[] fields2 = clazz.getFields();
        //获取所有Public方法 包括继承的
        Method[] methods = clazz.getMethods();
        
        for (Method method : methods) {
            String name = method.getName();
            if (name.matches("^get[A-Z\\_\\$]\\S*$")) {
                
            }
        }
        
        System.out.println(fields.length);
        for (Field field : fields) {
            System.out.println(field.getName());
        }
    }
    
    /**
     * 接口常量无法更改。
     * 不影响序列化和反序列化。所以不用管
     * @param clazz
     * @throws Exception 
     */
    public static void recursionClass(Class<? extends Object> clazz,Object obj) throws Exception{
        String clsName = clazz.getName();
        if ("java.lang.Object".equals(clsName)) {
            return ;
        }
        Map<String, Object> map = FIELD_VALUE.get();
        if (map == null) {
            map = new HashMap<>();
            //因为java字段不可能以数字开头命名。为了防止混淆，此处使用数字开头
            map.put(INDEX_KEY, 0);
            FIELD_VALUE.set(map);
        }
        Integer index = (int) map.get(INDEX_KEY) + 1;
        map.put(INDEX_KEY,index);
        map.put(index.toString(), clsName);
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(index + field.getName(),field.get(obj));
//            String name = field.getName();
//            System.out.println(name.getBytes());
//            System.out.println(field.getName() + "=" + field.get(obj));
        }
        if (clazz.getSuperclass() != null) {
            recursionClass(clazz.getSuperclass(),obj);
        }
    }
    
    public static void toJson(Object obj){
        System.out.println(JSON.toJSONString(obj));
    }
}
